package ro.upt.dcda.pricezone.s2.requests;

import java.util.List;

import javax.jms.JMSException;
import javax.jms.StreamMessage;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import ro.upt.dcda.pricezone.common.ConnectionFactory;
import ro.upt.dcda.pricezone.s2.S2;
import ro.upt.dcda.pricezone.s2.pojo.Store;

public class AllStoresRequest implements S2Request {

	private S2 instance;

	public AllStoresRequest(S2 instance) {
		this.instance = instance;
	}

	public void work(StreamMessage message) throws JMSException {
		Session session = ConnectionFactory.getFactory().openSession();
		try {

			Query query = session.createQuery("from Store");
			@SuppressWarnings("unchecked")
			List<Store> stores = (List<Store>) query.list();
			System.out.println("retrieved " + stores.size() + " stores");
			message.writeInt(stores.size());
			for (Store store : stores) {
				message.writeInt(store.getId());
				message.writeString(store.getName());
				message.writeString(store.getDescription());
				message.writeString(store.getLocation().toText());
				message.writeString(instance.getName());
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
}
